package com.taosdata.jdbc.springbootdemo.controller.tdengine;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taosdata.jdbc.springbootdemo.domain.jsonData.Data;
import com.taosdata.jdbc.springbootdemo.domain.jsonData.JsonRootBean;
import com.taosdata.jdbc.springbootdemo.domain.jsonData.SensorData;
import com.taosdata.jdbc.springbootdemo.domain.stables.SuperTable;
import com.taosdata.jdbc.springbootdemo.domain.thread.InsertThread;
import com.taosdata.jdbc.springbootdemo.service.tdengine.StableService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.select.SetOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zhmsky
 * @date 2022/9/25 14:28
 */
@RestController
@RequestMapping("/StableController")
@Api("普通数据接收")
@Slf4j
public class StableController {
    @Autowired
    private StableService stableService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;


    @PostMapping("/insert")
    public void insertCommonData(@RequestBody JSONObject jsonObject) {

        Object data = jsonObject.get("data");
        String jsonString = JSON.toJSONString(data);
        List<Data> Datas = JSON.parseArray(jsonString, Data.class);
        for (Data itemData : Datas) {
            String constructionId = itemData.getConstructionId();
            String monitorTypeId = itemData.getMonitorTypeId();
            String sensorId = itemData.getSensorId();
            List<SensorData> sensorData = itemData.getSensorData();
            CopyOnWriteArrayList<SuperTable> superTableList = new CopyOnWriteArrayList<>();
            for (SensorData sensorDatum : sensorData) {
                SuperTable superTable = new SuperTable();
                superTable.setConstructionId(constructionId);
                superTable.setMonitorTypeId(monitorTypeId);
                superTable.setSensorId(sensorId);
                superTable.setTs(new Timestamp(sensorDatum.getStampTime()));
                superTable.setDataValue(Float.valueOf(sensorDatum.getValue()));
                superTableList.add(superTable);
            }

            //入库
            if (!CollectionUtils.isEmpty(superTableList)) {
                threadPoolExecutor.execute(new InsertThread(superTableList));
            }
        }
    }

}